package com.yanfan.energy.service.impl;

import cn.hutool.core.util.StrUtil;
import com.yanfan.common.core.domain.model.LoginUser;
import com.yanfan.common.utils.SecurityUtils;
import com.yanfan.energy.domain.*;
import com.yanfan.energy.domain.enums.BatchesStatus;
import com.yanfan.energy.domain.enums.NumberUnitStatus;
import com.yanfan.energy.mapper.BatchSegmentationDao;
import com.yanfan.energy.mapper.BatchesDao;
import com.yanfan.energy.mapper.OrderDetailsDao;
import com.yanfan.energy.mapper.OrderLineDetailsDao;
import com.yanfan.energy.service.BatchesService;
import com.yanfan.energy.util.*;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Author huan
 * @Description 批次管理service层实现类
 * @ClassName 2023年01月09日 10:36:00
 * @Version 1.0
 **/
@Service
@Transactional(rollbackFor = Exception.class)
public class BatchesServiceImpl implements BatchesService {

    @Resource
    BatchesDao batchesDao;
    @Resource
    OrderLineDetailsDao orderLineDetailsDao;
    @Resource
    OrderDetailsDao orderDetailsDao;
    @Resource
    private BatchSegmentationDao batchSegmentationDao;

    @Override
    public List<Batches> batchesList(BatchesRequest request) {
        if (request.getMobileFlag() != null && request.getMobileFlag() && !SecurityUtils
                .getLoginUser()
                .getUser()
                .isAdmin()) {
//            request.setOperatorId(Math.toIntExact(SecurityUtils.getLoginUser().getUserId()));
        }
        List<Batches> batches = batchesDao.batchesList(request);
        if (CollectionUtils.isEmpty(batches)) {
            return batches;
        }
        Map<Long, Map<String, String>> factoryMap = batchesDao.queryFactoryMap();
        Map<Long, Map<String, String>> workshopMap = batchesDao.queryWorkshopMap();
        for (Batches batch : batches) {
            batch.setPlanName("M660型PCB生产计划");
            if (workshopMap != null && workshopMap.get(batch.getWorkshopId()) != null) {
                batch.setWorkshopName(workshopMap.get(batch.getWorkshopId()).get("name"));
            }
            if (factoryMap != null && factoryMap.get(batch.getPlantId()) != null) {
                batch.setPlantName(factoryMap.get(batch.getPlantId()).get("name"));
            }
        }
        return batches;
    }

    /**
     * 新增批次
     *
     * @param request
     * @return
     */
    @Override
    public int addBatches(BatchesRequest request) throws Exception {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        request.setCreatedBy(String.valueOf(loginUser.getUserId()));
        request.setCreatedDate(new Date());
        request.setLastModifiedDate(new Date());
        if (StrUtil.isEmpty(request.getOrderNumber())) {
            throw new Exception("订单号不为空");
        }
        OrderBody orderBody = new OrderBody();
        orderBody.setNumber(request.getOrderNumber());
        List<OrderLineDetails> orderParticularBodies = orderLineDetailsDao.findOrderLineDetails(orderBody);
        if (CollectionUtils.isEmpty(orderParticularBodies)) {
            throw new Exception("订单号不存在" + request.getOrderNumber());
        }
        OrderLineDetails orderLineDetails = orderParticularBodies.get(0);
        // 预计开始时间
        request.setBeginDate(orderLineDetails.getBeginDate());
        //   预计结束时间
        request.setEndDate(orderLineDetails.getEndDate());
        //   预计用时
        request.setTimeConsuming(orderLineDetails.getTimeConsuming());
        // 操作人
        request.setOperatorId(orderLineDetails.getOperatorId());
        request.setPrincipal(orderLineDetails.getPrincipal());

        request.setNumber(SerialNumberUtil.createBatchNo());
        int i = batchesDao.addBatches(request);
        List<BatchSegmentation> batchSegmentationList = request.getBatchSegmentationList();
        if (CollectionUtils.isEmpty(batchSegmentationList)) {
            return i;
        }
        for (BatchSegmentation batchSegmentation : batchSegmentationList) {
            // 批次ID
            batchSegmentation.setBatchId(request.getId());
            batchSegmentation.setBatchNumber(request.getNumber());
            // 分段编号
            batchSegmentation.setSegmentNumber(SerialNumberUtil.createSegmentNo());
            batchSegmentation.setBeginDate(request.getBeginDate()); // 预计开始时间
            batchSegmentation.setEndDate(request.getEndDate()); // 预计结束时间
            batchSegmentation.setTimeConsuming(request.getTimeConsuming()); // 预计完成时间

            // 产区选的和分段一样的
            batchSegmentation.setFactoryId(request.getPlantId());
            batchSegmentation.setCreatedBy(String.valueOf(loginUser.getUserId()));
            batchSegmentation.setCreatedDate(new Date());
            batchSegmentation.setLastModifiedDate(new Date());
        }
        return batchSegmentationDao.insertBatch(batchSegmentationList);
    }

    /**
     * 更新批次
     *
     * @param request
     * @return
     */
    @Override
    public int updateBatches(BatchesRequest request) {
        request.setLastModifiedDate(new Date());
        batchesDao.updateBatches(request);
        BatchSegmentationRequest batchR = new BatchSegmentationRequest();
        batchR.setBatchId(request.getId());
        // 数据库要删除的分段id
        List<Long> deleteIdArr = new ArrayList<>();
        List<Long> batchSegmentations = batchSegmentationDao.queryAllId(batchR);
        if (CollectionUtils.isNotEmpty(batchSegmentations)) {
            // 默认 数据库里面的都删除
            deleteIdArr = batchSegmentations;
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        // 用户提交的
        List<BatchSegmentation> batchSegmentationList = request.getBatchSegmentationList();
        if (CollectionUtils.isNotEmpty(batchSegmentationList)) {
            for (BatchSegmentation batchSegmentation : batchSegmentationList) {
                /**
                 * 前端传过来 就不删除
                 */
                if (deleteIdArr.contains(batchSegmentation.getId())) {
                    deleteIdArr.remove(batchSegmentation.getId());
                }
                // 批次ID
                batchSegmentation.setBatchId(request.getId());
                batchSegmentation.setBatchNumber(request.getNumber());
                // 分段编号
                batchSegmentation.setSegmentNumber(SerialNumberUtil.createSegmentNo());
                // 产区选的和分段一样的
                batchSegmentation.setFactoryId(request.getPlantId());
                batchSegmentation.setCreatedBy(String.valueOf(loginUser.getUserId()));
                batchSegmentation.setCreatedDate(new Date());
                batchSegmentation.setLastModifiedDate(new Date());
                // 设置创建的状态（刚创建为待生产）
                batchSegmentation.setState(1);
                // 设置初始值的开始时间和结束时间
                batchSegmentation.setBeginDate(new Date());
                batchSegmentation.setEndDate(new Date());
            }
            // 修改或者新增
            batchSegmentationDao.insertOrUpdateBatch(batchSegmentationList);
        }


        /**
         * 删除 要删除的
         */
        if (CollectionUtils.isNotEmpty(deleteIdArr)) {
            batchSegmentationDao.deleteByIds(deleteIdArr);
        }
        return 1;
    }

    /**
     * 批次详情
     *
     * @param request
     * @return
     */
    @Override
    public Batches batchesDetail(BatchesRequest request) {
        Batches batches = batchesDao.batchesDetail(request);
        if (batches == null) {
            return null;
        }
        BatchSegmentationRequest r = new BatchSegmentationRequest();
        r.setBatchId(request.getId());
        List<BatchSegmentation> batchSegmentations = batchSegmentationDao.queryAllByLimit(r);
        batches.setBatchSegmentationList(batchSegmentations);
        // todo 目前   写死
        batches.setPlanName("M660型PCB生产计划");
        return batches;
    }

    /**
     * 删除批次
     *
     * @param request
     * @return
     */
    @Override
    public int deleteBatches(BatchesRequest request) {
        return batchesDao.deleteBatches(request);
    }

    @Override
    public BatchSummaryResponse batchSummary() {
        BatchSummaryResponse response = new BatchSummaryResponse();
        List<BatchesInfo> batchesInfoList = batchesDao.batchesSummarizing();
        if (CollectionUtils.isEmpty(batchesInfoList)) {
            return response;
        }
        for (BatchesInfo batchesInfo : batchesInfoList) {
            if (BatchesStatus.PENDING.getCode().equals(batchesInfo.getType())) { // 待完成
                response.setPending(batchesInfo.getCount());
            } else if (BatchesStatus.IN_PRODUCTION.getCode().equals(batchesInfo.getType())) {
                response.setProcessed(batchesInfo.getCount());
            } else if (BatchesStatus.FINISHED.getCode().equals(batchesInfo.getType())) {
                response.setFinished(batchesInfo.getCount());
                response.setAverageTime(batchesInfo.getTimeFact());
            }
        }
        List<BatchesInfo> batchesInfos = packageTimeInfo();// 完成信息List
        if (CollectionUtils.isEmpty(batchesInfoList)) {
            return response;
        }
        response.setFinishingRate(BigDecimalUtil.divide(batchesInfos.size(), batchesDao.batchesListCount()));
        // 计算同步和环比
        response.setFinished(Long.valueOf(batchesInfos.size()));
        long the_month = 0L;
        long last_month = 0L;
        long last_year_last_month = 0L;
        for (BatchesInfo batchesInfo : batchesInfos) {
            if (DateUtils.getSomeMonth().equals(batchesInfo.getFactEndDateStr())) {
                the_month = batchesInfo.getCount();
            } else if (DateUtils.getTheBeforeMonth().equals(batchesInfo.getFactEndDateStr())) {
                last_month = batchesInfo.getCount();
            } else if (DateUtils.getLastYearMonth().equals(batchesInfo.getFactEndDateStr())) {
                last_year_last_month = batchesInfo.getCount();
            }
        }
        // 每批次平均用时，如果为空则设置为0
        if (Objects.isNull(response.getAverageTime())) {
            response.setAverageTime(0.00);
        }

        response.setOnYearOnYearBasis(BigDecimalUtil.divide((the_month - last_year_last_month), the_month));
        response.setLinkRelativeRatio((BigDecimalUtil.divide((the_month - last_month), last_month)));
        return response;
    }

    @Override
    public List<FactoryVo> factoryList() {
        return batchesDao.queryPlants();
    }

    @Override
    public List<WorkshopVo> workshopList(Integer plantId) {
        return batchesDao.queryWorkshopListByFactory(plantId);
    }

    @Override
    public Map<String, Object> managerHome() {
        // 年度 订单总数、订单总金额、生产计划总数
        Map<String, BaseDictEntity> yearInfoMap = orderLineDetailsDao.yearInfo();
        // 月 订单情况  待生产 生产中 已经完成数量
        Map<String, BaseDictEntity> monthScheduleMap = orderLineDetailsDao.monthScheduleInfo();
        // 批次、分段 已完成的数量
        Map<String, BaseDictEntity> batchSegmentMap = orderLineDetailsDao.batchSegmentInfo();
        // 任务处理  任务相关信息  (生产中)
        Map<String, BaseDictEntity> taskMap = orderLineDetailsDao.taskInfo();
        // 订单进度  所有的
        List<OrderLineDetails> orderLineDetails = orderLineDetailsDao.monthOrderInfo();
        Map responseMap = new HashMap();
        responseMap.put("yearInfoMap", initYearMap(yearInfoMap));
        responseMap.put("monthScheduleMap", initBaseDictMap(monthScheduleMap));
        responseMap.put("batchSegmentMap", batchSegmentInfoMap(batchSegmentMap));
        responseMap.put("taskMap", initBaseDictMap(taskMap));
        responseMap.put("orderLineDetails", orderLineDetails);
        return responseMap;
    }

    private List<BatchesInfo> packageTimeInfo() {
        /**
         * 当前时间
         */
        List<String> queryDateList = new ArrayList<>();
        queryDateList.add(DateUtils.getSomeMonth());
        queryDateList.add(DateUtils.getTheBeforeMonth());
        queryDateList.add(DateUtils.getLastYearMonth());
        return batchesDao.batchesFinishedRate(queryDateList);
    }

    private Map<String, BaseDictEntity> batchSegmentInfoMap(Map<String, BaseDictEntity> map) {
        if (map == null) {
            map = new HashMap<>();
        }
        mapFill(map, "batchNumber");
        mapFill(map, "segmentNumber");
        return map;
    }

    private Map<String, BaseDictEntity> initYearMap(Map<String, BaseDictEntity> map) {
        if (map == null) {
            map = new HashMap<>();
        }
        mapFill(map, "orderNumber");
        mapFill(map, "orderAmount");
        mapFill(map, "scheduleNumber");
        Map<String, Object> orderAmount = NumberUtils.amountConversion(Double.parseDouble(map
                                                                                                  .get("orderAmount")
                                                                                                  .getV()));
        Integer typeByUnit = NumberUnitStatus.getTypeByUnit((String) orderAmount.get(NumberConstant.NUMBER_UNITS));
        map.get("orderAmount").setType(typeByUnit);
        map.get("orderAmount").setV(String.valueOf(orderAmount.get(NumberConstant.NUMBER)));
        return map;
    }

    private Map<String, BaseDictEntity> initBaseDictMap(Map<String, BaseDictEntity> map) {
        if (map == null) {
            map = new HashMap<>();
        }
        mapFill(map, "pending");
        mapFill(map, "progress");
        mapFill(map, "finish");
        mapFill(map, "sum");
        mapFill(map, "overdue");
        return map;
    }

    private void mapFill(Map<String, BaseDictEntity> map, String k) {
        if (!map.containsKey(k)) {
            BaseDictEntity baseDictEntity = new BaseDictEntity();
            baseDictEntity.setK(k);
            baseDictEntity.setV("0");
            map.put(k, baseDictEntity);

        }
    }

}
